<extend name="Layout/ins_popup" />
<block name="content">
	<link href="__INS__/css/plugins/cropper/cropper.min.css" rel="stylesheet">
	<!-- Image cropper -->
	<div class="frame">
		<div class="" style="width:68%;float:left;">
			<div class="image-crop" style="margin-top:15px;margin-left:15px;margin-right:15px;">
				<img src="{$pic}">
			</div>
			<div id="test" src="" style="width:100px;height:100px;"></div>
		</div>
		<div class="text-center" style="width:29%;float:right;">
			<h4 style="margin-top:15px;">头像预览</h4>
			<div class="img-preview img-preview-sm avtar" style="margin-left:auto;margin-right:auto;margin-top:15px;"></div>
			<br>
			<br>
			<label title="Upload image file" for="inputImage" class="btn btn-primary">
				<input type="file" accept="image/*" name="file" id="inputImage" class="hidden">
				上传头像</label>
			<br><br><br>
			<a id="download" class="btn btn-primary">确定</a>
			<a id="btn_close" class="btn btn-cancel">关闭</a>
		</div>
	</div>
</block>
<block name="js">
	<script src="__INS__/js/jquery-2.1.1.js"></script>
	<script src="__INS__/js/plugins/cropper/cropper.min.js"></script>
	<script>
		var index = parent.layer.getFrameIndex(window.name);
		var $image = $(".image-crop > img");
		$($image).cropper({
			aspectRatio : 1,
			preview : ".img-preview",
			done : function(data) {
			}
		});

		var $inputImage = $("#inputImage");
		if (window.FileReader) {
			$inputImage.change(function() {
				var fileReader = new FileReader(), files = this.files, file;

				if (!files.length) {
					return;
				}

				file = files[0];

				if (/^image\/\w+$/.test(file.type)) {
					fileReader.readAsDataURL(file);
					fileReader.onload = function() {
						$inputImage.val("");
						$image.cropper("reset", true).cropper("replace", this.result);
					};
				} else {
					showMessage("Please choose an image file.");
				}
			});
		} else {
			$inputImage.addClass("hide");
		}

		$("#download").click(function() {
			var img_data = $image.cropper("getDataURL");
			var regS = new RegExp("\\+", "g");
			img_data = img_data.replace(regS, "_a");
			var regS = new RegExp("\\/", "g");
			img_data = img_data.replace(regS, "_b");
			var regS = new RegExp("\\=", "g");
			img_data = img_data.replace(regS, "_c");

			var vars = 'pic=' + img_data + '&id={$id}';
			var url = '{:U("save_avatar")}';
			$.ajax({
				type : "POST",
				url : url,
				data : vars,
				dataType : "json",
				success : function(ret) {
					if (ret.status) {
						var now = new Date();
						$('#pic', parent.document).attr('src', ret.pic + '?a=' + now.getTime());
						parent.layer.msg(ret.info);
						parent.layer.close(index);
					}
				}
			});
		});

		$("#btn_close").on('click', function() {
			parent.layer.close(index);
		});

	</script>
</block>
